package com.dd.shop4j.common.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * Excel公用类
 * 
 * @author Administrator
 *
 */
public class ExcelUtils {

	public static void writeExcel(OutputStream stream, List<List<Object>> datas) {
		HSSFWorkbook work = new HSSFWorkbook();
		HSSFSheet sheet = work.createSheet();
		for (int i = 0; i < datas.size(); i++) {
			List<Object> item = datas.get(i);
			HSSFRow row = sheet.createRow(i);
			for (int j = 0; j < item.size(); j++) {
				HSSFCell cell = row.createCell(j);
				Object value = item.get(j);
				if (value != null)
					cell.setCellValue(value.toString());
			}
		}
		try {
			work.write(stream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static List<List<Object>> getExcelData(Collection<?> datas) {
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {
			
			@Override
			public Object processObjectValue(String key, Object value, JsonConfig config) {
				return processArrayValue(value, config);
			}
			
			@Override
			public Object processArrayValue(Object value, JsonConfig config) {
				if (value instanceof Date) {
					return DateUtils.getYmdHmis((Date) value);
				}
				return null;
			}
		});
		JSONArray array = JSONArray.fromObject(datas, config);
		List<List<Object>> result = new ArrayList<List<Object>>();
		for (int i = 0; i < array.size(); i++) {
			JSONObject obj = array.getJSONObject(i);
			Set<String> keys = obj.keySet();
			List<Object> header = new ArrayList<Object>();
			//添加一下表头
			if (i == 0) {
				for (String key : keys) {
					header.add(key);
				}
			}
			result.add(header);
			
			List<Object> item = new ArrayList<Object>();
			for (String key : keys) {
				item.add(obj.get(key));
			}
			result.add(item);
		}
		return result;
	}
}
